function TabControl( prop ) {
    if( typeof prop.tabID != 'string' || prop.tabID == '' )
        return;

    this.tabID = prop.tabID;
    this.title = (typeof prop.title == 'string' ) ? prop.title : '';    
    this.show = (typeof prop.show == 'function' ) ? prop.show : function() {};
    this.hide = (typeof prop.hide == 'function' ) ? prop.hide : function() {};
    this.data = (typeof prop.data != 'undefined' ) ? prop.data : new Array();
    
    if( typeof prop.init == 'function' )
        prop.init( this.tabID );    
}

function TabSwitcher( tabsID ) {
    var tabs = new Array();
    var ts = this;
    var t = $('#'+tabsID).tabs( {
        select: function(ev,ui) {
            ts.onSwitchTo(ui.panel.id);
        }
    } );

    function index( tabID ) {
        var result;
        for( var i=0; i<tabs.length; i++) {
            if( tabs[i].tabID == tabID ) {
                result = i; break;
            }
        }
        return result;
    }
    
    this.find = function( tabID ) {
        var i = ( typeof(tabID) == 'string' && tabID != '') ? index( tabID ) : tabID;
        return tabs[i];
    }
    
    this.add = function( tab ) {
        if( typeof tab.tabID != 'string' || tab.tabID == '' ) return;
        if( typeof index( tab.tabID ) != 'undefined' ) return;

        var a = new Object();
        
        a.tabID = tab.tabID;
        a.title = (typeof tab.title == 'string' ) ? tab.title : a.tabID;    
        a.show  = (typeof tab.show == 'function' ) ? tab.show : function() {};
        a.hide  = (typeof tab.hide == 'function' ) ? tab.hide : function() {};
        a.data  = (typeof tab.data != 'undefined' ) ? tab.data : new Array();
    
        a.init  = (typeof tab.init == 'function' ) ? tab.init : function() {};
        a.destroy = (typeof tab.destroy == 'function' ) ? tab.destroy : function() {};
        tabs.push( a );

//        $('body').append('<div id='+a.tabID+' class=".ui-tabs .ui-tabs-hide"></div>');
        t.tabs('add','#'+a.tabID,a.title);

//		$('#'+a.tabID).width( $('#'+a.tabID).parent().innerWidth() - 2 );
//		$('#'+a.tabID).height( $('#'+a.tabID).parent().innerHeight() - 20 );

        a.init( a.tabID, tabs.length - 1 );    
    }
    
    this.remove = function( tabID ) {
        var i = ( typeof(tabID) == 'string' && tabID != '') ? index( tabID ) : tabID;
        var a =  tabs[i];
        
		if( i == t.tabs( "option", "selected" ) )
			this.SwitchTo( ( i == tabs.length - 1 ) ? i-1 : i+1 );
			
        a.destroy();
        tabs.splice(i,1);
        t.tabs('remove', i);
//        $('body > #'+a.tabID).remove();
        delete a;
    }
    
    this.onSwitchTo = function( tabID ) {
        var inew = ( typeof(tabID) == 'string' && tabID != '') ? index( tabID ) : tabID;
        var iold = t.tabs('option', 'selected');        
        tabs[iold].hide();
        tabs[inew].show();
    }
    
    this.SwitchTo = function( tabID ) {
        var i = ( typeof(tabID) == 'string' && tabID != '') ? index( tabID ) : tabID;
        t.tabs('select', i);        
    }
}

/*
function StyleSelect( dv ) {
    var bt = $('#'+dv);
    var sw;
    var swm;

    bt.css({'position':'absolute','top':'-841px','left':'-821px'});
    this.activate = function() { swm.dialog('open'); };

    bt.themeswitcher({
        loadTheme:'Smoothness',
        closeOnSelect: false,
        height:220,
        width:154,
        onOpen: function() {
            var divids = $('body > div');
            var pos;
            for( var i=0; i<divids.length; i++ ) {
                pos = $(divids[i]).position();
                if( pos.top == -821 && pos.left == -821 ) {
                    swm = $(divids[i]);
                    swm.attr('id','style_switcher_menu');
                    swm.unbind('mouseenter').unbind('mouseleave').unbind('mouseout');
                    swm.css({'position':'static', 'margin-top':'4px'});
                    swm.find('ul').css({'overflow-x':'hidden'});
                    swm.dialog({
                        modal: false, title: "Выберите тему",
                        height: 'auto', width: 'auto',
                        stack: true,
                        autoOpen: false, resizable: false,
                    });
                }
            }
        }
    });
     
    sw = $('.jquery-ui-themeswitcher-trigger');
    sw.trigger('click');
}
*/
function StyleSelect( dv ) {
    var bt = $('#'+dv);

//    bt.css({'position':'relative','top':'-841px','left':'-821px', 'padding':'0'});
    bt.css({'padding':'0'});
    this.activate = function() { bt.dialog('open'); };

    bt.themeswitcher({
        loadTheme:'Dark Hive',
		imgpath: "../js/sts/images/",
		rounded: false,
        closeonselect: false,
        height:320,
        width:200,
        onopen: function() {
					var swm = bt.find('.jquery-ui-switcher-list-hldr');
                    swm.unbind('mouseenter').unbind('mouseleave').unbind('mouseout');
                    swm.css({'position':'static', 'margin-top':'4px'});
                    swm.find('ul').css({'overflow-x':'hidden'});

                    bt.dialog({
                        modal: false, title: "Выберите тему",
                        height: 'auto', width: 'auto',
                        stack: true,
                        autoOpen: false, resizable: false,
                    });

                }
    });

	$('#'+dv+' .jquery-ui-switcher-link').trigger('click').css({'display':'none'}); 
}

//    function ViewOptions(dombut, dlgID) {
function ViewOptions( par ) {
    var dlgID = par.optdlg_id;
	var areaID = par.show_area_id;
	var rows = par.rows;
	var cols = par.cols;
	var sort = par.sort;
	var cbfunc = par.cbfunc;
    var col_width = 300;
    var col_dist = 20;
    var str_default = 3;
    var col_default = 3;

	SetViewGrid = function(str, col, srt) {
        var n, i;
        var cells, tds;
        var st = $('#'+areaID+' table');

        if (!str) str = str_default;
        if (!col) col = col_default;

        cells = '';
        for (n = 0; n < str; n++) {
            tds = '';
            for (i = 0; i < col; i++) tds = tds + '<td role="SearchRes_Unit"></td>';
            cells = cells + '<tr>' + tds + '</tr>';
        }
        st.html(cells);
        st.css({ 'width': col * (col_width + col_dist) - col_dist, 'border-spacing': col_dist });
        
        rows = str;
		cols = col;
		sort = srt;
        if( typeof cbfunc == 'function' ) cbfunc();
    };

	this.GetData = function() {
		return { rows:rows, cols:cols, sort:sort };
	};
	
	this.ShowDialog = function() {
	    var aldlg = $('#' + dlgID);

	    aldlg.html(
                '<p>Количество строк: <span id="strnum"></span></p>' +
                '<div id="rowslider"></div></br>' +
                '<p>Количество столбцов: <span id="colnum"></span></p>' +
                '<div id="colslider"></div></br>' +
                '<p>Сортировать по: <select id="viewgridsort">' +
					'<option value="city_name" >Регион продажи</option>' +
					'<option value="vend_name" >Марка автомобиля</option>' +
                    '<option value="model_name">Модель автомобиля</option>' +
                    '<option value="p_date">Год выпуска</option>' +
                    '<option value="km_count">Пробег</option>' +
                    '<option value="price"   >Цена автомобиля</option>' +
                '</select></p>'
        );

	    $('#viewgridsort option[value="' + sort + '"]').attr('selected', 'selected');

	    $("#rowslider").slider({ value: rows, min: 1, max: 10, step: 1,
	        slide: function (event, ui) { $("#strnum").text(ui.value); }
	    });
	    $("#strnum").text($("#rowslider").slider("value"));

	    $("#colslider").slider({ value: cols, min: 1, max: 10, step: 1,
	        slide: function (event, ui) { $("#colnum").text(ui.value); }
	    });
	    $("#colnum").text($("#colslider").slider("value"));

	    aldlg.dialog(
        {
            modal: true, title: "Опции просмотра",
            height: 'auto', width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Применить": function () {
                    var newsort = $('#viewgridsort').val();
                    SetViewGrid(
                        $("#rowslider").slider("value"),
                        $("#colslider").slider("value"),
                        $('#viewgridsort').val()
                    );
                    $(this).dialog("close");
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    aldlg.dialog('open');
	}
		
    $('#'+areaID).append('<table></table>');
	SetViewGrid( rows, cols, sort);
}

function RegUser(par) {
    var dlgID = par.dlg_id;
	var areaID = par.data_area_id;

	this.Register = function() {
	    var dlg = $('#' + dlgID);

	    dlg.html(
		'<div style="height:280px; width:320px; padding:16px;"> \
        <div id="profile_mess" class="ui-widget ui-corner-all ui-widget-content" \
		style="position:absolute; width:320px; bottom:0px; left:50%; margin-left:-168px; \
		padding: 4px 8px; text-align:center; display:none;"></div> \
        <form id="profile_form" > \
	    <table table-layout:fixed;style="width:100%"><col style="width:48%"><col style="width:4%"><col style="width:48%"> \
        <tr><td colspan="3"><label for="uname">Как к Вам обращаться</label><br> \
        <input type="text" name="uname" id="uname" style="width:310px;"/></td></tr> \
        <tr><td colspan="3"><label for="email">Укажите Ваш E-Mail адрес\
		<span style="font-size:smaller;">( Желательно, находящийся на публичном сервере. Как то: mail.ru, gmail.com, и т.д. )</span></label><br> \
        <input type="text" name="email" id="email"  style="width:310px;" /></td></tr> \
        <tr><td><label for="passw">Пароль<br><span style="font-size:smaller;">( Не менее 6-ти символов )</span></label><br> \
        <input type="password" name="passw" id="passw"  style="width:144px;" /></td><td></td> \
        <td><label for="passw_re">Пароль<br><span style="font-size:smaller;">( Введите повторно )</span></label><br> \
        <input type="password" name="passw_re" id="passw_re"  style="width:144px;" /></td></tr> \
        <tr><td><label for="phone_code">Номер телефона<br><span style="font-size:smaller;">( только цифры )</span></label><br> \
        ( <input type="text" name="phone_code" id="phone_code" style="width:24px;" /> ) \
		<input type="text" name="phone_num" id="phone_num" style="width:92px; float:right;"/></td><td></td><td></td></tr> \
        <tr><td><label for="captcha">Код на картинке<br><span style="font-size:smaller;">( Пять символов )</span></label><br> \
        <input type="text" name="captcha" id="captcha"  style="width:144px;" /></td> \
		<td></td><td id="cap_img"></td></tr> \
		</table></form></div>'
        );

//		$("form#profile_form :input").addClass("ui-widget-content ui-corner-all");
        $("form#profile_form #cap_img").html(
            '<img src="utils/secpic.php?q='+Math.random()+'" />' +
            '<a class="app-capReload ui-state-default ui-corner-all" href="#">'+
            '<span class="ui-icon ui-icon-refresh"></span></a>'
        );
        $('a.app-capReload').bind('click', function () {
                $("form#profile_form #cap_img img").attr('src','utils/secpic.php?q='+Math.random() );
                return false;
        })
        .hover( function() { $(this).addClass("ui-state-hover"); }, 
                function() {$(this).removeClass("ui-state-hover"); });
		
        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                $('#profile_mess').html(rsp.errmess)
                    .removeClass("ui-state-default")
                    .addClass("ui-state-error")
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#profile_mess').fadeOut('normal')}, 5000 );
                    });                
                return;
            }
            else {
                dlg.dialog("close");
                $('#' + dlgID + ' *').remove();
                app.alert('AlertDlg', 'Поздравляем', rsp.data, 'ipdepo-icon-info32');
                return;
            }
        }
                 
	    dlg.dialog(
        {
            modal: true, title: "Регистрация",
            height: 400, width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Отправить": function () {
                    var reqData = {
                        source: 'Customer',
                        oper: 'register',
                        uname: $('#profile_form #uname').val(),
                        email: $('#profile_form #email').val(),
                        passw: $('#profile_form #passw').val(),
                        passw_re: $('#profile_form #passw_re').val(),
                        phone: $('#profile_form #phone_code').val()+$('#profile_form #phone_num').val(),
                        captcha: $('#profile_form #captcha').val()
                    };
                    
                    $.post('callbacks.php', reqData, reqResp, 'json' );
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    dlg.dialog('open');
	}

	this.Login = function() {
	    var dlg = $('#' + dlgID);

	    dlg.html(
		'<div style="height:150px; width:200px; padding:16px;"> \
        <div id="login_mess" class="ui-widget ui-corner-all ui-widget-content" \
		style="position:absolute; width:200px; bottom:0px; left:50%; margin-left:-108px; \
		padding: 4px 8px; text-align:center; display:none;"></div> \
        <form id="login_form"> \
		<table style="width:100%"> \
		<tr><td><div class="ipdepo-icon-png32 ipdepo-icon-keys32"></div></td> \
		<td><span style="text-shadow: 1px 1px #bbbbbb;">Введите ваши данные</span></td></tr> \
	    <tr><td colspan="2"><label for="email">E-Mail</label><br> \
        <input type="text" name="email" id="email" style="width:100%" /></td></tr> \
        <tr><td colspan="2"><label for="passw">Пароль</label><br> \
        <input type="password" name="passw" id="passw" style="width:100%" /></td></tr> \
		</table></form></div>'
        );

        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                $('#login_mess').html(rsp.errmess)
                    .removeClass("ui-state-default")
                    .addClass("ui-state-error")
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#login_mess').fadeOut('normal')}, 5000 );
                    });                
                return;
            }
            else {
                dlg.dialog("close");
                $('#' + dlgID + ' *').remove();
				app.customer.uname = rsp.data.uname;
				app.TabSw.add( {
					tabID: 'CustomerData',
					title: app.customer.uname,
					init: function() { 
							app.CarsCatalogue.Open('CustomerData');
							$('#CustomerData').parent().bind('tabsshow', function(event, ui) {
								if (ui.panel.id == "CustomerData") {
									app.CarsCatalogue.Resize();
								}
							});
					},
					show: function() {},
					hide: function() {}, 
					destroy: function() { app.CarsCatalogue.Close(); }
				} );
				app.TabSw.SwitchTo('CustomerData');
                return;
            }
        }
                 
	    dlg.dialog(
        {
            modal: true, title: "Вход",
            height: 'auto', width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Войти": function () {
                    var reqData = {
                        source: 'Customer',
                        oper: 'login',
                        email: $('#login_form #email').val(),
                        passw: $('#login_form #passw').val()
                    };
                    
                    $.post('callbacks.php', reqData, reqResp, 'json' );
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    dlg.dialog('open');
	}

	
	this.Logout = function() {
        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
                return;
            }
            else {
				app.customer.uname = '';
				app.TabSw.remove('CustomerData');
                return;
            }
        }
        $.post('callbacks.php', { source: 'Customer', oper: 'logout' }, reqResp, 'json' );                 
	}
	
	this.Update = function() {
        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
                else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'ipdepo-icon-stop32');
            }
            else
                DoUpdate( rsp.data );
        }
        $.post('callbacks.php', { source: 'Customer', oper: 'read' }, reqResp, 'json' );                 
	}
	
	function DoUpdate(parm) {
	    var dlg = $('#' + dlgID);

	    dlg.html(
		'<div style="height:230px; width:320px; padding:16px;"> \
        <div id="profile_mess" class="ui-widget ui-corner-all ui-widget-content" \
		style="position:absolute; width:320px; bottom:0px; left:50%; margin-left:-168px; \
		padding: 4px 8px; text-align:center; display:none;"></div> \
        <form id="profile_form" > \
	    <table table-layout:fixed;style="width:100%"><col style="width:48%"><col style="width:4%"><col style="width:48%"> \
        <tr><td colspan="3"><label for="uname">Как к Вам обращаться</label><br> \
        <input type="text" name="uname" id="uname" style="width:310px;" /></td></tr> \
        <tr><td colspan="3"><label for="email">Укажите Ваш E-Mail адрес\
		<span style="font-size:smaller;">( Желательно, находящийся на публичном сервере. Как то: mail.ru, gmail.com, и т.д. )</span></label><br> \
        <input type="text" name="email" id="email" style="width:310px;" /></td></tr> \
        <tr><td><label for="passw">Пароль<br><span style="font-size:smaller;">( Не менее 6-ти символов )</span></label><br> \
        <input type="password" name="passw" id="passw" style="width:144px;" /></td><td></td> \
        <td><label for="passw_re">Пароль<br><span style="font-size:smaller;">( Введите повторно )</span></label><br> \
        <input type="password" name="passw_re" id="passw_re" style="width:144px;" /></td></tr> \
        <tr><td><label for="phone_code">Номер телефона<br><span style="font-size:smaller;">( только цифры )</span></label><br> \
        ( <input type="text" name="phone_code" id="phone_code" style="width:24px;" /> ) \
		<input type="text" name="phone_num" id="phone_num" style="width:92px; float:right;"/></td><td></td><td></td></tr> \
		</table></form></div>'
        );

		$('#profile_form #uname').val( parm.uname );
		$('#profile_form #email').val( parm.email );
		$('#profile_form #phone_code').val( parm.phone.substr(0,3) );
		$('#profile_form #phone_num').val( parm.phone.substr(3) );
		
        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                if (rsp.errcode == '999') { 
					alert(rsp.errmess);
					app.customer = { uname:'', cust_id:0 };
					location.href = 'index.php'; 
				}
                $('#profile_mess').html(rsp.errmess)
                    .removeClass("ui-state-default")
                    .addClass("ui-state-error")
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#profile_mess').fadeOut('normal')}, 5000 );
                    });
                return;
            }
            else {
                dlg.dialog("close");
                $('#' + dlgID + ' *').remove();
                app.alert('AlertDlg', 'Поздравляем', rsp.data, 'ipdepo-icon-info32');
                return;
            }
        }
                 
	    dlg.dialog(
        {
            modal: true, title: "Редактирование профиля",
            height: 350, width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Отправить": function () {
                    var reqData = {
                        source: 'Customer',
                        oper: 'update',
                        uname: $('#profile_form #uname').val(),
                        email: $('#profile_form #email').val(),
                        passw: $('#profile_form #passw').val(),
                        passw_re: $('#profile_form #passw_re').val(),
                        phone: $('#profile_form #phone_code').val() + $('#profile_form #phone_num').val()
                    };
                    
                    $.post('callbacks.php', reqData, reqResp, 'json' );
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    dlg.dialog('open');
	}

	this.Restore = function() {
	    var dlg = $('#' + dlgID);

	    dlg.html(
		'<div style="height:84px; width:200px; padding:16px;"> \
        <div id="login_mess" class="ui-widget ui-corner-all ui-widget-content" \
		style="position:absolute; width:200px; bottom:0px; left:50%; margin-left:-108px; \
		padding: 4px 8px; text-align:center; display:none;"></div> \
        <form id="login_form"> \
		<table style="width:100%"> \
	    <tr><td><label for="email">Укажите заданный Вами при регистрации E-Mail адрес</label><br> \
        <input type="text" name="email" id="email" /></td></tr> \
		</table></form></div>'
        );

        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                $('#login_mess').html(rsp.errmess)
                    .removeClass("ui-state-default")
                    .addClass("ui-state-error")
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#login_mess').fadeOut('normal')}, 5000 );
                    });                
                return;
            }
            else {
                dlg.dialog("close");
                $('#' + dlgID + ' *').remove();
                app.alert('AlertDlg', 'Уведомление', rsp.data, 'ipdepo-icon-info32');
                return;
            }
        }
                 
	    dlg.dialog(
        {
            modal: true, title: "Восстановление пароля",
            height: 204, width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Отправить": function () {
                    var reqData = {
                        source: 'Customer',
                        oper: 'restore',
                        email: $('#login_form #email').val()
                    };
                    
                    $.post('callbacks.php', reqData, reqResp, 'json' );
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    dlg.dialog('open');
	}

	this.AdminMail = function() {
	    var dlg = $('#' + dlgID);

	    dlg.html(
		'<div style="height:280px; width:320px; padding:16px;"> \
        <div id="amail_mess" class="ui-widget ui-corner-all ui-widget-content" \
		style="position:absolute; width:320px; bottom:0px; left:50%; margin-left:-168px; \
		padding: 4px 8px; text-align:center; display:none;"></div> \
        <form id="amail_form" > \
	    <table style="table-layout:fixed; width:100%;"><col style="width:48%"><col style="width:4%"><col style="width:48%"> \
        <tr><td colspan="3"><label for="uname">Как к Вам обращаться</label><br> \
        <input type="text" name="uname" id="uname" style="width:310px;"/></td></tr> \
        <tr><td colspan="3"><label for="email">Укажите Ваш E-Mail адрес\
		<span style="font-size:smaller;">( Этот адрес будет использован для ответа на ваше сообщение )</span></label><br> \
        <input type="text" name="email" id="email"  style="width:310px;" /></td></tr> \
        <tr><td colspan="3"><label for="mess_text">Ваше сообщение</label><br> \
        <textarea name="mess_text" id="mess_text" style="width:310px;height:100px;"></textarea></td></tr> \
        <tr><td><label for="captcha">Код на картинке<br><span style="font-size:smaller;">( Пять символов )</span></label><br> \
        <input type="text" name="captcha" id="captcha"  style="width:144px;" /></td> \
		<td></td><td id="cap_img"></td></tr> \
		</table></form></div>'
        );

        $("form#amail_form #cap_img").html(
            '<img src="utils/secpic.php?q='+Math.random()+'" />' +
            '<a class="app-capReload ui-state-default ui-corner-all" href="#">'+
            '<span class="ui-icon ui-icon-refresh"></span></a>'
        );
        $('a.app-capReload').bind('click', function () {
                $("form#amail_form #cap_img img").attr('src','utils/secpic.php?q='+Math.random() );
                return false;
        })
        .hover( function() { $(this).addClass("ui-state-hover"); }, 
                function() {$(this).removeClass("ui-state-hover"); });
		
        function reqResp(rsp, textStatus) {
            if (rsp.errcode) {
                $('#amail_mess').html(rsp.errmess)
                    .removeClass("ui-state-default")
                    .addClass("ui-state-error")
                    .fadeIn('slow', function() {
                        setTimeout( function() { $('#amail_mess').fadeOut('normal')}, 5000 );
                    });                
                return;
            }
            else {
                dlg.dialog("close");
                $('#' + dlgID + ' *').remove();
                app.alert('AlertDlg', 'Сделано', rsp.data, 'ipdepo-icon-info32');
                return;
            }
        }
                 
	    dlg.dialog(
        {
            modal: true, title: "Сообщение для администратора",
            height: 400, width: 'auto',
            zIndex: app.ui_dialog_min_z_index,
            autoOpen: false, resizable: false,
            open: function () { $('div[aria-labelledby="ui-dialog-title-' + dlgID + '"]').shadow() },
            close: function () {
                $(this).dialog("destroy");
                $.ui.dialog.maxZ = $.maxZIndex({ group: '.ui-dialog.ui-widget' });
            },
            buttons: {
                "Отправить": function () {
                    var reqData = {
                        source: 'Customer',
                        oper: 'amail',
                        uname: $('#amail_form #uname').val(),
                        email: $('#amail_form #email').val(),
                        text:  $('#amail_form #mess_text').val(),
                        captcha: $('#amail_form #captcha').val()
                    };
                    
                    $.post('callbacks.php', reqData, reqResp, 'json' );
                },
                "Отмена": function () {
                    $(this).dialog("close");
                    $('#' + dlgID + ' *').remove(); 
                }
            }
        });

	    dlg.dialog('open');
	}

}
